package com.atguigu.gulimall.product.web;

import com.alibaba.nacos.common.util.UuidUtils;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {
    @Autowired
    CategoryService categoryService;
    @Autowired
    RedissonClient redisson;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @GetMapping({"/","index.html"})
    public String indexPage(Model model){
        // TODO 1、查出所有1级分类
        List<CategoryEntity> categoryEntitys = categoryService.getLevel1Categorys();
        model.addAttribute("categorys",categoryEntitys);
        return "index";
    }
//index/catalog.json
    @ResponseBody
    @GetMapping("index/catalog.json")
    public Map<String,List<Catelog2Vo>>getCatalogJson() throws InterruptedException {
        Map<String,List<Catelog2Vo>>map=categoryService.getCatalogJson();
        return map;
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        //1.获取一把锁，只要锁的名字一样，就是同一把锁
        RLock lock = redisson.getLock("my-lock");
        //2.加锁:两个优点，阻塞等待，自动续期，不用担心业务时间长被删除，
        // 默认时间长是30秒，业务执行完成后会解锁，即使我们不unlock也会业务执行完后进行解锁。
     //lock.lock(5, TimeUnit.SECONDS);//设置自动解锁时间，自动解锁时间一定要大于业务执行时间。时间到了不会自动续期的。
        //最佳实践：lock.lock(5, TimeUnit.SECONDS);设置时间，最长就是等这么长，没有什么事情。
        try {
            System.out.println("加锁成功，执行业务……" + Thread.currentThread().getId());
            Thread.sleep(30000);
            lock.lock();
            //开门狗当时间过了10秒时自动续期到30s
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {//执行不到这里，也会自动解锁，不会造成死锁。
            System.out.println("解锁成功" + Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }

//改数据加写锁，读数据加读锁。保证一定能读到最新数据。修改期间，写锁是一个排他锁，互斥锁。读锁是共享锁。只要写锁存在，必须
    //读锁就不行。
    //读-读锁，共享锁，相当于没有回销。
    //写-读，或写-写模式，阻塞
    //读-写模式，读完才能写。
    //总结：有读锁，写也需要等待；有写锁，都需要等待； 读读不需要等待。

    @ResponseBody
    @GetMapping("/write")
    public String writeValue() {
        RReadWriteLock lock=redisson.getReadWriteLock("rw-lock");
        String s = "";
        RLock wLock = lock.writeLock();

        try {
            wLock.lock();
            System.out.println("写锁加锁成功，执行业务……" + Thread.currentThread().getId());
            s = UuidUtils.generateUuid().toString();

            Thread.sleep(30000);
            stringRedisTemplate.opsForValue().set("writeValue",s);

            //开门狗当时间过了10秒时自动续期到30s
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
        wLock.unlock();
        System.out.println("写锁解锁" + Thread.currentThread().getId());

        }
        return s;
    }

    @ResponseBody
    @GetMapping("/read")
    public String read() {
        String s = "";
        RReadWriteLock lock=redisson.getReadWriteLock("rw-lock");
        RLock rLock = lock.readLock();
        rLock.lock();//加读锁
        try {
            System.out.println("读锁加锁成功" + Thread.currentThread().getId());
            s=stringRedisTemplate.opsForValue().get("writeValue");
            Thread.sleep(30000);
        } catch (Exception ignored) {

        } finally {
        rLock.unlock();
        System.out.println("读锁解锁" + Thread.currentThread().getId());
        }
        return s;
    }

    @ResponseBody
    @GetMapping("lockDoor")
    public String lockDoor() throws InterruptedException {
        RCountDownLatch door=redisson.getCountDownLatch("door");
        door.trySetCount(5);
        door.await();
        return "放假了……";
    }

    @ResponseBody
    @GetMapping("gogogo/{id}")
    public String gogogo(@PathVariable("id") Long id)  {
        RCountDownLatch door=redisson.getCountDownLatch("door");
        door.countDown();//计数减1；
        return  id+"班的人走了";
    }

//信号量,可以用作分布式限流
    @ResponseBody
    @GetMapping("park")
    public String park()  {
        RSemaphore park=redisson.getSemaphore("park");
//        park.acquire();//获取一个信号，占一个车位，阻塞式
        boolean b= park.tryAcquire();
        return "停车成功=>"+b;
    }

    @ResponseBody
    @GetMapping("go")
    public String g() throws InterruptedException {
        RSemaphore park=redisson.getSemaphore("park");
        park.release();
        return  "开走一辆车,增加了一个空车位";
    }






}
